package com.usoft;

import akka.dispatch.ExecutionContexts;
import akka.dispatch.Futures;
import akka.dispatch.Mapper;
import scala.concurrent.Await;
import scala.concurrent.ExecutionContextExecutorService;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;

import java.util.concurrent.Executors;

/**
 * Created by liyanxin on 2015/1/8.
 */
public class FutureDemo4 {

    public static void main(String args[]) throws Exception {

        final ExecutionContextExecutorService ec = ExecutionContexts.fromExecutorService(
                Executors.newCachedThreadPool());
        final Future<String> f1 = Futures.successful("com/hello");
        final Future<String> f2 = Futures.successful("world");

        //如果要对多个Future的结果进行处理，需要用flatMap
        //本例中对f1和f2返回的结果用空格连接成“com.hello world”
        Future<String> fr = f1.flatMap(new Mapper<String, Future<String>>() {
            public Future<String> apply(final String s) {
                return f2.map(new Mapper<String, String>() {
                    @Override
                    public String apply(String v) {
                        return s + " " + v;
                    }
                }, ec);
            }
        }, ec);

        //阻塞在这里，等待结果处理完成
        System.out.println(Await.result(fr, Duration.create(5, "s")));
    }
}
